<?php
namespace app\one_api\api;
use think\Controller;
use think\Response;
use think\Db;
use think\exception\HttpResponseException;
use app\one_api\model\OneApi as apiModel;
/**
 * 框架公共控制器
 * @package app\common\controller
 */
class ApiInit extends Controller
{
    public $params = [];
    public $_params = [];
    public $token = '';
    protected function initialize() {
        //接收参数
        $tmp = input();
        if ($this->params) {
            $tmp = [];
            foreach ($this->params as $key => $value) {
                $tmp[$key] = trim($value);
            }
        }
        $this->params = $this->_params = $tmp;
        //授权码
        $this->secret = request()->header('secret');
        //登录后的token
        $this->token = request()->header('token');
        //时间戳
        $this->timestamp = request()->header('timestamp');
        $this->timestamp = substr($this->timestamp, 0, 10);
        // if(!isset($this->secret)) {
        //     $this->_error('缺少参数: secret', [], -401);
        // }
        // if(!isset($this->timestamp) || abs(time()-$this->timestamp)>30 ) {
        //     $this->_error('缺少参数: timestamp 或请求超时！', [], -416);
        // }
        // if(!apiModel::vaildSecret($this->secret)) {
        //     $this->_error('非法请求', [], -401);
        // }
    }

    public function _success($msg = 'success', $data = [], $code=0 ,$header = [], $type = 'json') {
        $this->_result($msg, $data, $code, $header, $type);
    }

    public function _error ($msg = 'error', $data = [], $code=1, $header = [], $type = 'json') {
        $this->_result($msg, $data, $code,  $header,  $type);
    }

    /**
     * 返回封装后的API数据到客户端
     * @access protected
     * @param  mixed     $data 要返回的数据
     * @param  integer   $code 返回的code
     * @param  mixed     $msg 提示信息
     * @param  string    $type 返回数据格式
     * @param  array     $header 发送的Header信息
     * @return void
     */
    public function _result($msg = '', $data= [], $code = 0, array $header = [], $type = 'json')
    {
        $mtime = Db::name('system_config')->order('update_time DESC')->find();
        $header['config-update_time']  = $mtime['update_time'];
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
        $response = Response::create($result, $type);
        throw new HttpResponseException($response);
    }


}
